package com.bayair.doctor.ui.personal;

import android.app.Activity;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.bayair.doctor.R;
import com.bayair.doctor.utils.log.KLog;
import com.tencent.imsdk.TIMCallBack;
import com.tencent.imsdk.TIMFriendshipManager;
import com.tencent.imsdk.TIMUserProfile;
import com.tencent.imsdk.TIMValueCallBack;
import com.tencent.imsdk.friendship.TIMFriend;
import com.tencent.qcloud.tim.uikit.component.CircleImageView;
import com.tencent.qcloud.tim.uikit.component.LineControllerView;
import com.tencent.qcloud.tim.uikit.component.picture.imageEngine.impl.GlideEngine;
import com.tencent.qcloud.tim.uikit.modules.chat.base.ChatInfo;
import com.tencent.qcloud.tim.uikit.modules.contact.ContactItemBean;
import com.tencent.qcloud.tim.uikit.utils.ToastUtil;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import androidx.annotation.Nullable;

public class PersonalLayout extends LinearLayout implements View.OnClickListener {

    private static final String TAG = "PersonalLayout";

    private CircleImageView mHeadImageView;
    private TextView mNickNameView;
    private LineControllerView mRemarkView;
    private TextView mChatView;

    private ChatInfo mChatInfo;
    private String mId;
    private ContactItemBean mContactInfo;

    private OnButtonClickListener mListener;

    public PersonalLayout(Context context) {
        super(context);
        init();
    }

    public PersonalLayout(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public PersonalLayout(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        inflate(getContext(), R.layout.layout_personal, this);

        mHeadImageView = findViewById(R.id.avatar);
        mNickNameView = findViewById(R.id.name);
        mRemarkView = findViewById(R.id.remark);
        mRemarkView.setOnClickListener(this);
        mChatView = findViewById(com.tencent.qcloud.tim.uikit.R.id.btnChat);
        mChatView.setOnClickListener(this);
    }

    /**
     设置初始化值
     @param data
     */
    public void initData(Object data) {
        mChatInfo = (ChatInfo) data;
        mId = mChatInfo.getId();
        loadUserProfile();
        return;
    }

    private void loadUserProfile() {
        ArrayList<String> list = new ArrayList<>();
        list.add(mId);
        final ContactItemBean bean = new ContactItemBean();
        bean.setFriend(false);
        TIMFriendshipManager.getInstance().getUsersProfile(list, false, new TIMValueCallBack<List<TIMUserProfile>>() {
            @Override
            public void onError(int i, String s) {
                KLog.e(TAG, "loadUserProfile err code = " + i + ", desc = " + s);
                ToastUtil.toastShortMessage("Error code = " + i + ", desc = " + s);
            }

            @Override
            public void onSuccess(List<TIMUserProfile> timUserProfiles) {
                if (timUserProfiles == null || timUserProfiles.size() != 1) {
                    return;
                }
                final TIMUserProfile profile = timUserProfiles.get(0);
                bean.setNickname(profile.getNickName());
                bean.setId(profile.getIdentifier());
                bean.setAvatarurl(profile.getFaceUrl());
                updateViews(bean);
            }
        });

        TIMFriendshipManager.getInstance().getFriendList(new TIMValueCallBack<List<TIMFriend>>() {
            @Override
            public void onError(int i, String s) {
                KLog.e(TAG, "getFriendList err code = " + i + ", desc = " + s);
                ToastUtil.toastShortMessage("Error code = " + i + ", desc = " + s);
            }

            @Override
            public void onSuccess(List<TIMFriend> timFriends) {
                if (timFriends != null && timFriends.size() > 0) {
                    for (TIMFriend friend : timFriends) {
                        if (TextUtils.equals(friend.getIdentifier(), mId)) {
                            bean.setFriend(true);
                            bean.setRemark(friend.getRemark());
                            bean.setAvatarurl(friend.getTimUserProfile().getFaceUrl());
                            break;
                        }
                    }
                }
                updateViews(bean);
            }
        });
    }


    private void updateViews(ContactItemBean bean) {
        mContactInfo = bean;
        mId = bean.getId();
        String nickname = bean.getNickname();
        if (!TextUtils.isEmpty(nickname)) {
            mNickNameView.setText(nickname);
        } else {
            mNickNameView.setText(mId);
        }
        if (bean.isFriend()) {//只有好友才能修改昵称，调用modifyFriends接口会改变好友关系
            mRemarkView.setVisibility(VISIBLE);
            mRemarkView.setContent(bean.getRemark());
        } else {
            mRemarkView.setVisibility(GONE);
        }
        if (!TextUtils.isEmpty(bean.getAvatarurl())) {
            GlideEngine.loadImage(mHeadImageView, Uri.parse(bean.getAvatarurl()));
        }
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.btnChat) {
            chat();
        }  else if (v.getId() == R.id.remark) {
            Bundle bundle = new Bundle();
            bundle.putString(TextSettingActivity.TEXT_SETTING_TITLE,getResources().getString(R.string.profile_remark_edit));
            bundle.putString(TextSettingActivity.TEXT_SETTING_CONTENT,mRemarkView.getContent());
            TextSettingActivity.actionStart(bundle,text -> {
                mRemarkView.setContent(text);
                modifyRemark(text);
            });


        }
    }

    private void chat() {
        if (mListener != null || mContactInfo != null) {
            mListener.onStartConversationClick(mContactInfo);
        }
        ((Activity) getContext()).finish();
    }

    //调用modifyFriends接口会改变好友关系
    private void modifyRemark(final String txt) {
        HashMap<String, Object> hashMap = new HashMap<>();
        // 修改好友备注
        hashMap.put(TIMFriend.TIM_FRIEND_PROFILE_TYPE_KEY_REMARK, txt);
        TIMFriendshipManager.getInstance().modifyFriend(mId, hashMap, new TIMCallBack() {
            @Override
            public void onError(int i, String s) {
                KLog.e(TAG, "modifyRemark err code = " + i + ", desc = " + s);
            }

            @Override
            public void onSuccess() {
                mContactInfo.setRemark(txt);
                KLog.i(TAG, "modifyRemark success");
            }
        });
    }

    public void setOnButtonClickListener(OnButtonClickListener l) {
        mListener = l;
    }

    public interface OnButtonClickListener {
        void onStartConversationClick(ContactItemBean info);
    }
}
